<template>
  <!-- 这里拷贝的 /src/modules/task/view/components/TaskCard/components/CardEditDialog.vue的文件内容因为不想改拆源组件内容索性复制了一份 -->
  <div class="add-ons-form">
    <div class="add-ons-form__content">
      <form-builder 
        ref="form" 
        :fields="fields" 
        :value="form" 
        @update="update"
        :mode="`${mode}_card`">
        <!-- start 备件 --> 
        <template slot="taskCardRelationProduct" slot-scope="{ field, value }">
          <!-- start 客户字段 -->
          <form-item :label="field.displayName">
            <div class="input-and-btn">
              <biz-remote-select
                :value="value"
                :field="customerField"
                :remote-method="searchCustomer"
                @input="updateCustomer"
                :placeholder="$t('task.tip.keywordTip')"
                :computed-width-keys="['name']"
              >
                <div
                  class="customer-template-option"
                  slot="option"
                  slot-scope="{ option }"
                >
                  <!-- <h3>{{ option.name }}</h3> -->
                  <p>
                    <label>{{$t('common.base.name')}}：</label>
                    <span>{{ option.name }}</span>
                  </p>
                  <p>
                    <label>{{$t('common.form.preview.sparepart.colum2')}}：</label>
                    <span>{{ option.serialNumber }}</span>
                  </p>
                </div>
              </biz-remote-select>
            </div>
          </form-item>
        </template>
        <!-- end 备件 -->

        <!-- start 产品 -->
        <template slot="additionalProduct" slot-scope="{ field, value }">
          <form-item :label="$t('common.label.product')">
            <product-search 
              class="additional-product"
              ref="searchProductRef"
              :placeholder='$t("common.placeholder.selectProduct")'
              :value="value"
              :remote-method="searchProductFetch"
              @focus="handleRestOptionValue"
              @update="handleUpdateFormValue($event, 'additionalProduct')">
            </product-search>
          </form-item>
        </template>


        <template slot="additionalCustomer" slot-scope="{ field, value }">
          <form-item :label="$t('common.label.customer')" :is-not-null="!field.isNull">
            <customer-search 
              class="additional-customer"
              ref="searchCustomerRef"
              :placeholder='$t("common.placeholder.selectCustomer")'
              :value="value"
              :remote-method="searchCustomerFetch"
              @update="handleUpdateFormValue($event, 'additionalCustomer')">
            </customer-search>
          </form-item>
        </template>



        <!-- start 用时时间 -->
        <template slot="usedTime" slot-scope="{ field, value }" v-if="isHoursRecord">
          <form-item :label="field.displayName">
            <input
              class="usedTime"
              type="number"
              :value="value"
              :placeholder="field.placeHolder"
              disabled />
          </form-item>
        </template>
        <!-- end 用时时间 -->

        <!-- start 行程距离 -->
        <template slot="distance" slot-scope="{ field }" v-if="isHoursRecord">
          <form-item :label="field.displayName">
            <input
              class="distance"
              type="number"
              v-model="form.distance"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" />
          </form-item>
        </template>
        <!-- end 行程距离 -->
      </form-builder>
    </div>
    <div class="add-ons-footer">
      <el-button @click="handleClose" :disabled="buttonDisabled">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit" :disabled="buttonDisabled">{{$t('common.base.save')}}</el-button>
    </div>
  </div>
</template>

<script>
import { ConnectorModuleConnectorCreateAddonsMixin } from '@src/modules/connector';
/* util */
import * as Utils from '@src/component/form/util';
import { getQueryTaskProduct } from '@src/api/TaskApi';

import FieldComponents from '@src/component/AdvancedSearch/FieldComponents'

import { searchProduct, searchCustomer } from '@src/component/AdvancedSearch/advancedSearch'

import { cloneDeep } from 'lodash'

export default {
  name: 'AddOnsForm',
  mixins: [ConnectorModuleConnectorCreateAddonsMixin],
  components: {
    [FieldComponents.productSearch.name]: FieldComponents.productSearch,
    [FieldComponents.customerSearch.name]: FieldComponents.customerSearch
  },
  props: {
    fields: {
      type: Array,
      default: () => ([])
    },
    value: {
      type: Object,
      default: () => ({
        attribute: {}
      })
    },
    task: {
      type: Object,
      default: () => ({
        attribute: {}
      })
    },
    isHoursRecord: {
      type: Boolean,
      default: false
    },
    action: {
      type: String,
      default: ''
    },
    mode: {
      type: String,
      default: ''
    },
    buttonDisabled: {
      type: Boolean,
      default: false
    }
  },
  inheritAttrs: false,
  data() {
    return {
      visible: false,
      init: true,
      form: {},
      isWatchUpdate: false,
      customerField: {
        isSystem: 1,
        fieldName: 'customer',
        displayName: this.$t('common.base.product'),
        formType: 'customer',
        defaultValue: null,
        isNull: 0,
        isSearch: 0,
        placeHolder: null,
      },
    }
  },
  computed: {
    /**
    * @description 弹窗标题
    */
    title() {
      return this.action == 'edit' ? this.$t('task.detail.components.editComponentInfo') : this.$t('task.detail.components.addComponentInfo');
    }
  },

  watch: {
    form: {
      handler(n) {
        if(Reflect.has(n, 'additionalProduct') && n.additionalProduct?.[0]?.id && !this.isWatchUpdate) {
          this.$nextTick(()=> {
            this.$refs.searchProductRef.handleSetDefaultValue('', n.additionalProduct?.[0]?.id || '', n.additionalProduct?.[0]?.customerId || '')
            this.isWatchUpdate = true
          })
        }
      },
      deep: true
    }
  },
  methods: {
    handleUpdateFormValue(v, key = 'additionalProduct') {
      this.$set(this.form, key, v)
    },
    handleRestOptionValue() {
      const additionalProductV = this.form?.additionalProduct 
      if(additionalProductV && Array.isArray(additionalProductV) && additionalProductV.length === 0) {
        this.$refs.searchProductRef?.keywordSearch()
      }
    },
    async searchProductFetch(params = {}) {
      return searchProduct(params)
    },
    async searchCustomerFetch(params = {}) {
      return searchCustomer(params)
    },
    handleClose() {
      this.removeConnectorCreateSessionData()
      this.postCloseDialogMessage()
    },
    async searchCustomer(params) {
      try {
        params = {
          taskId: this.task.id,
          ...params
        }
        let result = await getQueryTaskProduct(params);
        result.list = result.result
        if (!result || !result.list) return;
        result.list = result.list.map((data) =>
          this.selectConversion(data)
        );
        return result;
      } catch (error) {
        console.warn(`${this.$options.name}: searchData -> error`, error);
      }
    },
    selectConversion(obj) {
      if(!obj) return {};
    
      let { name, id } = obj;
  
      return Object.freeze({
        label: name,
        value: id,
        ...obj
      })
    },
    updateCustomer(e) {
      this.form.taskCardRelationProduct = e;
    },
    /**
    * @description 更新表单数据
    */
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;

      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`)
      }

      this.$set(this.form, fieldName, newValue);

      // 计算工时记录用时时间
      if (this.isHoursRecord) {
        if (fieldName == 'startTime' || fieldName == 'endTime') this.setUsedTime();
      }
    },
    /**
    * @description 弹窗关闭重置数据
    */
    reset() {
      this.form = {};
      this.init = false;
    },
    /**
    * @description 将数据拆解成自定义表单可接收的数据
    */
    unpack() {
      let { attribute = {} } = this.value;
      let result = Utils.initialize(this.fields, { attribute });
      this.form = result;
      if(this.form.taskCardRelationProduct){
        this.form.taskCardRelationProduct = [this.form.taskCardRelationProduct]
      }
    },
    /**
    * @description 表单验证
    */
    submit() {
      this.$refs.form
        .validate(false)
        .then(async valid => {
          if (!valid) return Promise.reject('validate fail.');
          // 判断工时记录的开始时间和结束时间
          if (this.isHoursRecord) {
            let { startTime, endTime } = this.form;
            if (startTime && endTime && startTime > endTime) return this.$platform.alert(this.$t('customer.detail.taskCard.cartEditDialog.submit.timeAlert'));
          }
          const cloneForm = cloneDeep(this.form)

          if(Array.isArray(cloneForm.additionalCustomer)) {
            cloneForm.additionalCustomer = cloneForm.additionalCustomer?.[0] || {}
          }
          this.$emit('submit', { ...this.connectorMessageData, param: cloneForm});
        })
        .catch(err => {
          console.error(err);
        })
    },
    /** 
    * @description 计算用时时间
    * 结束时间-开始时间
    */
    setUsedTime() {
      let { startTime, endTime } = this.form;
      if (startTime && endTime) {
        let diff = (Math.abs(endTime - startTime) / 1000 / 60 / 60).toFixed(2);

        this.$set(this.form, 'usedTime', +diff);
      }
    }
  }
}
</script>

<style lang="scss">
.add-ons-form{
    height: 100%;
    background: #fff;
    overflow-y: auto ;
    &__content{
        height: 100%;
        box-sizing: border-box;
        padding-bottom: 60px;
    }
}
.base-window-content,
.task-card-edit-dialog {
  .usedTime,
  .distance {
    width: 100%;
  }
}
.customer-template-option{
  padding: 10px 0;
}
.customer-template-option p{
  line-height: 30px;
    margin: 0
}
.add-ons-footer{
    position: absolute;
    right: 20px;
    bottom: 20px;
}
.additional-product, .additional-customer {
  .el-select  {
      width: 100%;
  }
}
</style>
